import * as ol from "ol";
import { mapInstance } from "./instance";
import { log } from "./log";
import type { AnimationOptions, FitOptions } from "./types";
import { isEmpty } from "ol/extent";
import type { Extent } from "ol/extent";
import type { SimpleGeometry } from "ol/geom";
import { queryExtentByFeatures, queryExtentByQuery } from "./extent";
/**
 * @description: 移动地图视角
 * @param {AnimationOptions} options 配置项
 * @returns
 */
export const panTo = (options: AnimationOptions): void => {
  if (mapInstance) {
    mapInstance.getView().animate(options);
    log("Pan To", options);
  }
};
/**
 * @description: 获取视图实例
 * @returns {ol.View}
 */
export const getView = (): ol.View | undefined => {
  if (mapInstance) {
    return mapInstance.getView();
  }
};
/**
 * @description: 根据几何图形或者边界调整视角
 * @param {SimpleGeometry|Extent} geometryOrExtent 几何元素或者边界
 * @param {FitOptions} options 配置项
 * @returns
 */
export const fitViewByGeometryOrExtent = (
  geometryOrExtent: SimpleGeometry | Extent,
  options?: FitOptions
): void => {
  if (mapInstance) {
    mapInstance.getView().fit(geometryOrExtent, options);
    log("Fit View", {
      geometryOrExtent,
      ...options,
    });
  }
};

/**
 * @description: 通过元素移动地图视角
 * @param {ol.Feature|Array<ol.Feature>} features 元素或者元素列表
 * @param {FitOptions} options 配置项
 * @returns
 */
export const fitViewByFeatures = (
  features: ol.Feature[] | ol.Feature,
  options?: FitOptions
): void => {
  if (mapInstance) {
    const extent = queryExtentByFeatures(features);
    if (!isEmpty(extent)) {
      mapInstance.getView().fit(extent, options);
      log("Fit View", {
        features,
        ...options,
      });
    }
  }
};
/**
 * @description: 通过查询移动地图视角
 * @param {Object} query 查询参数
 * @param {FitOptions} options 配置项
 * @returns
 */
export const fitViewByQuery = (
  query: { features?: string[]; layers?: string[] },
  options?: FitOptions
): void => {
  if (!mapInstance) {
    return;
  }
  const extent = queryExtentByQuery(query);
  if (!isEmpty(extent)) {
    mapInstance.getView().fit(extent, options);
    log("Fit View", {
      query,
      ...options,
    });
  }
};
